﻿/// <reference path="../SignalR/jquery.signalR-2.2.2.min.js" />
/// <reference path="../SignalR/jquery.signalR-2.2.2.min.js" />



$.MGJ.Common = [];

//溯源版本可能要用到的url溯源路径和ID
var LoadUrl_Url, RootsId, RootsUrl;

//微信支付页未支付去除定时器的参数
var wxPayPage;

//导出数据参数
var info = [];

//adminindex定时器
var MapTimer

//左侧菜单//点击菜单载入页面
(function () {
    var _this = $.MGJ.Common;
    $.extend($.MGJ.Common, {
        loadurl: function (t, url, limitUpd, limitDel, limitAdd) {
            //营销填写数据，但离开页面的提示
            if (sessionStorage.getItem('alertSave'))
            {
                var r = confirm("温馨提示！离开本页面不会保存当前数据！");
                if (r == true) {//点击确定
                    sessionStorage.setItem('isLeave', true);
                    sessionStorage.removeItem('alertSave');
                }
                else {//点击取消
                    sessionStorage.setItem('isLeave', false);
                    return;
                }
            }
            
            //重置导出数据参数
            info = [];

            if (wxPayPage) {
                window.clearInterval(iCount);
                wxPayPage = "";
            }
            $(".big-right").css("margin-top", "40px")
            //LoadUrl_Url-"返回"的需要的路径
            LoadUrl_Url = url;
            if (url != '/Manager/AdminIndex')//去掉首页定时器  勿动
            {
                clearInterval(MapTimer);
            }
          
            $('.main .big-right').load(url);
            if ($(t).find($(".site-menu-title")).length > 0) {
                $("#admui-siteConTabs").show().find($(".active")).remove()
                var $li = '<li class="Nb-con-tabs active"><a data-pjax="" rel="contents"><span>' + $(t).find($(".site-menu-title")).text() + '</span></a ></li>'
                $("#admui-siteConTabs").find($(".con-tabs")).append($li);
            }
           
            $("#admui-siteConTabs").show();

            window.limitUpd = limitUpd || 1;
            window.limitDel = limitDel || 1;
            window.limitAdd = limitAdd || 1;
        },
        TLM_LoadUrl: function (t, url) {
            $('.TLM_LoadUrl').load(url);
        },
        Init: function () {
            $('.main .big-left').css('height', window.innerHeight - 60);
            $(window).resize(function () {
                $('.main .big-left').css('height', window.innerHeight - 60);
            });
            $('#menu li.site-menu-item.has-sub.first')
                .hover(function () {
                    //打开
                    if ($(document.body).hasClass("site-menubar-unfold")) {
                        $(this).removeClass('hover').siblings(".first").removeClass("hover");
                    }
                    //折叠
                    else if ($(document.body).hasClass("site-menubar-fold")) {
                        $(this).addClass('hover').siblings(".first").removeClass("hover");
                    }
                })
                .click(function (e) {
                    $(this).toggleClass('open').siblings(".first").removeClass("open");
                    if($(this).hasClass('open'))
                    {
                        $('.tab-pane.animation-fade .link-con').addClass('ShowCompanyInfo');
                        $('.main #bigBox').removeClass('ShowCompanyInfo');
                    }
                    else {
                        $('.tab-pane.animation-fade .link-con').removeClass('ShowCompanyInfo');
                        $('.main #bigBox').addClass('ShowCompanyInfo');
                    }
                    e.stopPropagation();
                }).mouseleave(function () {
                    $(this).removeClass('hover').siblings(".first").removeClass("hover");

                });
            $('#menu li.site-menu-item.has-sub.second').click(function (e) {
                $(this).toggleClass('open').siblings(".second").removeClass("open");
                e.stopPropagation();
            });
            $('#menu .site-menu-sub li.site-menu-item').click(function (e) {
                if (sessionStorage.getItem('isFirst') == 'true')
                {
                    if (sessionStorage.getItem('isLeave')=='true')
                    {
                        $('#menu .site-menu-sub li.site-menu-item').removeClass('site-menu-active');
                        $(this).addClass('site-menu-active');
                        sessionStorage.removeItem('isFirst');
                        sessionStorage.removeItem('isLeave');
                    }
                    else {
                        return;
                    }
                   
                }
                else {
                    $('#menu .site-menu-sub li.site-menu-item').removeClass('site-menu-active');
                    $(this).addClass('site-menu-active');
                }
        
                
                




                var SiteMenuSubIndex = $(this).parents('.site-menu-item.has-sub.first.open').index();
                var MenuActivityIndex = $(this).index();
                sessionStorage.setItem('SiteMenuSubIndex', SiteMenuSubIndex);
                sessionStorage.setItem('MenuActivityIndex', MenuActivityIndex);
                //console.log(SiteMenuSubIndex+'------'+MenuActivityIndex);
                e.stopPropagation();
             
            });
        },
        _PrewView: function (materialId, batchId) {
            //if (parseInt($(obj).attr("materialId")) > 0 || parseInt($(obj).attr("id")) > 0 || parseInt(obj)>0) {
            //    var materialId = $(obj).attr("materialId") || $(obj).attr("id") || obj;
            //}
            var materialId = materialId;
            var batchId = batchId;
            var html = [
                '<!-- 模态框声明 -->',
                '<div id="myModal">',
                '    <!-- 窗口声明 -->',
                '    <div style="text-align: center;width: 150px;border-radius: 4px;background: #FFFFFF;left: 50%;margin-left: -300px;top: 50%;margin-top: -320px;z-index: 99999;position: fixed;border-radius: 4px;">',
                '	    <div style="background: #f0f0f0;line-height: 15px;padding: 10px 0;border-top-right-radius: 4px;border-top-left-radius: 4px;;">',
                '			<div style="font-size: 12px;">与实际手机显示效果</div>',
                '		    <div style="font-size: 12px;">有微小差异，请扫码查看</div>',
                '	    </div>',
                '	    <div style="margin: 10px auto;" id="qr_code"></div>',
                //'	    <a href=' + qrsting + ' style="padding-bottom: 20px;display: block;font-size: 12px;word-wrap:break-word;">' + qrsting + '</a>',
                '    </div>',
                '    <div style="text-align: center;width: 150px;border-radius: 4px;background: #FFFFFF;left: 50%;margin-left: -300px;top: 50%;margin-top: -115px;z-index: 99999;position: fixed;border-radius: 4px;">',
                '	    <div style="background: #f0f0f0;line-height: 15px;padding: 10px 0;border-top-right-radius: 4px;border-top-left-radius: 4px;;">',
                '			<div style="font-size: 14px;">当前预览模拟</div>',
                '	    </div>',
                '	    <div style="margin: 10px auto;">',
                '            <select id="phone-model" onchange="$.MGJ.ProductBatch.ChangeModel(this)" style="font-size: 16px;border-radius: 4px;margin: 10px;background-color:#f0f0f0;padding:5px">',
                '              <option value="iphone7">苹果 7</option>',
                '              <option value="iphone7plus">苹果 7 Plus</option>',
                '            </select>',
                '       </div>',
                '    </div>',
                '    <img style="position: fixed;top: 76px;left: 50%;margin-left: 300px;width:36px;height:36px;z-index:99999" src="/Content/webImgs/TraceSource/TraceSourceEdit/iPhone-X.png"  data-dismiss="modal" />',
                '    <div class="iphone" id="iphoneViews" style="background-image: url(/Content/webImgs/TraceSource/TraceSourceEdit/iPhone.png);background-size: 100% 64px;width:375px;height:681px;">',
                '       <div style="width:100%;height:100%;position:relative">',
                '            <iframe id="playBox" class="playBox" style="overflow-y:auto;width:100%;height:100%"></iframe>',
                '       </div>',
                '    </div>',
                '</div>'].join("");

            if ($("#myModal").length <= 0) {
                $("body").append(html);
            }

            var src = "/MaterialPreview/ViewCenter?materialId=" + materialId + "&batchId=" + batchId;
            $("#playBox").attr("src", src);

            var qrstring = document.origin + src;
            //console.log(qrstring);
            //二维码
            $("#qr_code").children().remove();

            $("#qr_code").qrcode({
                width: 120, //宽度
                height: 120, //高度
                //text: qrsting //任意内容
                text: qrstring
            });
            
            $('#myModal').modal('show');
            $("[class='modal-backdrop in']").click(function () {
                $('#myModal').modal('hide');
            });
        }
    });

})(jQuery);

//读取缓存中激活的菜单信息
function getActivityMenu() {
    
    var SiteMenuSubIndex = sessionStorage.getItem('SiteMenuSubIndex');
    var MenuActivityIndex = sessionStorage.getItem('MenuActivityIndex');
    if (SiteMenuSubIndex && MenuActivityIndex)
    {
        $('#menu li.site-menu-item.has-sub.first').eq(SiteMenuSubIndex).addClass('open').children('ul.site-menu-sub').children('li.site-menu-item').eq(MenuActivityIndex).addClass('site-menu-active').click();
        //console.log('SiteMenuSubIndex:' + SiteMenuSubIndex);
        //console.log('MenuActivityIndex:' + MenuActivityIndex);
    }
}
getActivityMenu();

//定时清除缓存中激活的菜单信息 8分钟
//setInterval(clearActivityMenu,8*60*1000);


function clearActivityMenu() {
    var SiteMenuSubIndex = sessionStorage.getItem('SiteMenuSubIndex');
    var MenuActivityIndex = sessionStorage.getItem('MenuActivityIndex');
    if (SiteMenuSubIndex && MenuActivityIndex) {
        sessionStorage.removeItem('SiteMenuSubIndex');
        sessionStorage.removeItem('MenuActivityIndex');
    }
}


//顶部导航
function MenuBarClick() {
    if ($(document.body).hasClass("site-menubar-unfold")) {
        $('#menu li.site-menu-item.has-sub.first').removeClass("open");
        $('#menu li.site-menu-item.has-sub.second').removeClass("open");
        $('#menu li.site-menu-item.first  span.glyphicon.glyphicon-menu-right').hide();
        $(document.body).removeClass("site-menubar-unfold").addClass("site-menubar-fold");
    } else if ($(document.body).hasClass("site-menubar-fold")) {
        $('#menu li.site-menu-item.first  span.glyphicon.glyphicon-menu-right').show();
        $(document.body).removeClass("site-menubar-fold").addClass("site-menubar-unfold");
    }
    $('.main .big-left').toggleClass('small-left').find('.link-con').toggle();
}



$(document).on("click", function (e) {
    //顶部自建功能(换色 头像)
    if (!$(e.target).closest(".animation-scale-up").length) {
        $("#admui-navbarDisplay").removeClass("open")
        $("#head_portrait_li").removeClass("open")
    }
    if (!$(e.target).closest(".time_div").length) {
        $(".time_div").hide()
    }
})
    //.on("click", "#admui-navbarDisplay,#head_portrait_li,#admui-navbarMessage", function (e) {

//    if ($(e.target).closest(".animation-scale-up").length) {

//        $(this).removeClass("open")
//    } else {

//        if ($(this).find('#messageCount').text().length>0)
//        {
//            $(this).find('#messageCount').text('');
//        }
//        $(this).addClass("open");
//    }
//    e.stopPropagation()
//})
    .on("click", ".wb-layout", function (e) {
        if ($("#admui-navbarDisplay").hasClass("open")) {
            $(".open").removeClass("open")
        } else {
            $(".open").removeClass("open")
            $("#admui-navbarDisplay").addClass("open");
        }
        e.stopPropagation()
    }).on("click", "#nav_layout", function (e) {
        e.stopPropagation()
    }).on("click", ".nav-change-color", function () {
        $(".site-navbar").css("background-color", $(this).children("a").css("background-color"));

        var colorindex = $(".nav-change-color").index($(this))
        for (var i = 0; i < $(".nav-change-color").length; i++) {
            $(document.body).removeClass("bodycolor" + i)
        }
        $(document.body).addClass("bodycolor" + colorindex)

    }).on("mousemove", "#nav_layout", function () {
        $(this).parent().next("div").hide()
    }).on("click", "#admui-navbarFullscreen", function (element) {
        //点击全屏
        var docElm = document.documentElement;
        if (document.body.scrollHeight == window.screen.height && document.body.scrollWidth == window.screen.width) {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            }
            else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            }
            else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            }
            else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        } else {
            //W3C  
            if (docElm.requestFullscreen) {
                docElm.requestFullscreen();
            }
                //FireFox  
            else if (docElm.mozRequestFullScreen) {
                docElm.mozRequestFullScreen();
            }
                //Chrome等  
            else if (docElm.webkitRequestFullScreen) {
                docElm.webkitRequestFullScreen();
            }
                //IE11
            else if (elem.msRequestFullscreen) {
                elem.msRequestFullscreen();
            }
        }
    })
//清空消息数字
$('#admui-navbarMessage').click(function () {
    if ($(this).find('#messageCount').text().length > 0) {
        $(this).find('#messageCount').text('');
        if (_messageReadId != null && _messageReadId.length > 0) {
            $.ajax({
                type: "POST",
                url: ACTION_URL("SetUserMessageToRead", "Home"),
                data: { messageId: _messageReadId.join(",") },
                cache: false,
                success: function () {
                    //alert("OK");
                    messageCount = 0;
                }
            });
        }
    }
})


//换头像
function change_file() {
      

    var r = new FileReader();
    f = document.getElementById('head_portrait').files[0];
    r.readAsDataURL(f);
    r.onload = function (e) {
        $("#head_portrait_label").attr("src", this.result);
        $("#head_portrait_label_show").attr("src", this.result);
        $.ajax({
            type:"post",
            url: ACTION_URL("EditUserInfo", "Manager"),
            data: { UserImg: this.result },
            success: function () {
                //alert("OK");
                messageCount = 0;
            }
        });
   
       
    };
  
}
//手机预览模块
$("#admui-QRcode").on("click", function () {
    var $layer = '<div class="modal-backdrop fade in" id="qrcode_layer"></div>'
    if (!$(document.body).hasClass("modal-open")) {
        $(document.body).addClass("modal-open").append($layer).find($("#admui-mobileView").addClass("in").css("display", "block"))
    }
})
$("#admui-mobileView").on("click", function () {
    $(document.body).removeClass("modal-open").find($("#admui-mobileView").removeClass("in").css("display", "none"))
    $("#qrcode_layer").remove()
})



//非空验证
function EmptyValidation(event) {

    $(".EmptyValidationText").each(function () {
        if ($(this).val() == "" || $(this).val() == "--请选择--") {
            $.L.msgError("有*项文本框或选择框未填写");
            event.preventDefault();

        }
    })

    $(".EmptyValidationNub").each(function () {
        if ($(this).val() == "" && parseFloat($(this).val()) > 0) {
            $.L.msgError("输入数字项不符合")
            evente.preventDefault();

        }
    })

    $(".EmptyValidationCheckbox").each(function () {
        var a = 0;
        for (var i = 0; i < $(this).find("input").length; i++) {
            if ($(this).find('input').eq(i).is(":checked")) {
                a++;
            }
        }
        if (a == 0) {
            $.L.msgError("有*选择项未选择");
            event.preventDefault();

        }
    })
}
//全选
$(document).on("click", ".AllClickCheckbox", function () {
    if (this.checked) {
        $(".AllClickChild").prop("checked", true).change();
    } else {
        $(".AllClickChild").prop("checked", false).change();
    }
})

var all_checked;
$(document).on("click", ".AllClickChild", function () {
    var AllClickChildLength = $(".AllClickChild").length
    var Num = 0;
    all_checked = this.checked

    $(".AllClickChild").each(function () {
        if ($(this).prop("checked") == all_checked) {
            Num++
        }
    })

    if (Num == AllClickChildLength) {
        $(".AllClickCheckbox").prop("checked", all_checked)
    } else {
        !all_checked ? $(".AllClickCheckbox").prop("checked", all_checked) : $(".AllClickCheckbox").prop("checked", !all_checked)
    }
})
//溯源路径和id
function RootsPathAndID(_this) {
    RootsId = $(_this).attr("materialId") || $(_this).attr("id")
    RootsUrl = LoadUrl_Url;
}
function UrlBack() {
    $.MGJ.Common.loadurl(this, RootsUrl)
}
//更多搜索
function detailSearch(ele) {
    $('.detail-search-con').slideToggle();
    $(ele).prev().toggle().prev().toggle().prev().toggle();
    $(ele).prevAll('input').val('');
}

function removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}

function ConvertJSONDateToJSDateObject(jsondate) {
    var date = new Date(parseInt(jsondate.replace("/Date(", "").replace(")/", ""), 10));
    return date;
}

var messageCount = 0;
var _messageReadId = [];
function MessageSignalR() {
    try {
     
        var chat = $.connection.ab403fada0dc4c19ba2beb47f375f8ef;
        chat.client.sendMessage = function (_r) {
            try {
                var r = JSON.parse(_r);
                if (r && r.ReciveUserId == window.UserId) {
                    messageCount += 1;
                    $("#messageCount").text(messageCount);
              
                    if (r.PushContent.indexOf("您有商品尚待召回，请查阅清单") != -1) {
                        $("#admui-messageContent").append("<a class='list-group-item' onclick='Detail(0)' data-message-id='" + r.ID + "' data-title='欢迎您访问Admui演示系统' data-content='通过websocket实时推送给前端用户。' role='menuitem'><div class='media'><div class='media-left padding-right-10'><i class='glyphicon glyphicon-bullhorn' aria-hidden='true'>" +
                    "</i></div><div class='media-body'><h6 class='media-heading'>" + r.PushContent + "</h6>" +
                    "<p class='media-meta' datetime='" + r.PushDate + "'> " + r.PushDateString + "</p></div></div></a>")
                    }

                    else if (r.PushContent.indexOf("您有码申请信息暂未处理，请查阅清单") != -1) {
                        $("#admui-messageContent").append("<a class='list-group-item' onclick='Detail(1)' data-message-id='" + r.ID + "' data-title='欢迎您访问Admui演示系统' data-content='通过websocket实时推送给前端用户。' role='menuitem'><div class='media'><div class='media-left padding-right-10'><i class='glyphicon glyphicon-bullhorn' aria-hidden='true'>" +
                    "</i></div><div class='media-body'><h6 class='media-heading'>" + r.PushContent + "</h6>" +
                    "<p class='media-meta' datetime='" + r.PushDate + "'> " + r.PushDateString + "</p></div></div></a>")
                    }
                    else {
                        $("#admui-messageContent").append("<a class='list-group-item' href='#' data-message-id='" + r.ID + "' data-title='欢迎您访问Admui演示系统' data-content='通过websocket实时推送给前端用户。' role='menuitem'><div class='media'><div class='media-left padding-right-10'><i class='glyphicon glyphicon-bullhorn' aria-hidden='true'>" +
                                                            "</i></div><div class='media-body'><h6 class='media-heading'>" + r.PushContent + "</h6>" +
                                                            "<p class='media-meta' datetime='" + r.PushDate + "'> " + r.PushDateString + "</p></div></div></a>")
                    }
                    if (r.IsRead == 0) {
                        _messageReadId.push("'" + r.ID + "'");
                    }
                }
            } catch (e) {
                $("#messageCount").text(messageCount);
            }
        };
        $.connection.hub.start().done();
    } catch (e) {
    }
}

setTimeout(function () {
    MessageSignalR();
}, 1000);


function Detail(type) {

    if (type == 0) {
        $.MGJ.Common.loadurl(this, '/CodeManage/antifleeing_distributorrecalllogList', '0', '0', '0')
    }
   else if (type ==1) {
       $.MGJ.Common.loadurl(this, '/CodeManage/AllotCode', '0', '0', '0')
    }
}
//去除 空格 回车 换行
function removeSpace(testStr) {
    if (testStr)
    {
        var testStr = testStr.replace(/\ +/g, ""); //去掉空格
        testStr = testStr.replace(/[ ]/g, "");    //去掉空格
        testStr = testStr.replace(/[\r\n]/g, ""); //去掉回车换行
        return testStr;
    }
}



